<template>
  <el-container style="padding: 20px">
    <el-main>
      <!-- 搜索区 -->
      <el-row>
        <el-col :span="24">
          <el-card>
            <el-form :inline="true" class="search-form">
              <el-form-item label="疫苗编号：">
                <el-input
                  v-model="searchVaccine.vaccineNumbering"
                  placeholder="请输入疫苗编号"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button @click="search" type="primary">
                  <el-icon><Search /></el-icon>
                  <span>搜索</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <!-- 表格区 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card>
            <el-header class="table-header" style="justify-content: flex-start">
              <el-button @click="handleSave" type="primary">
                <el-icon><CirclePlus /></el-icon>
                添加疫苗
              </el-button>
            </el-header>

            <el-table :data="vaccineData" style="width: 100%">
              <el-table-column label="ID" width="80">
                <template #default="{ $index }">
                  {{ (currentPage - 1) * pageSize + $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="疫苗名称" width="120" />
              <el-table-column prop="numbering" label="疫苗编号" width="120" />
              <el-table-column prop="amount" label="数量" width="80" />
              <el-table-column label="生产时间" width="105">
                <template #default="{ row }">{{
                  formatDate(row.productionDate)
                }}</template>
              </el-table-column>
              <el-table-column label="失效时间" width="105">
                <template #default="{ row }">{{
                  formatDate(row.inactivationDate)
                }}</template>
              </el-table-column>
              <el-table-column label="检测时间" width="105">
                <template #default="{ row }">{{
                  formatDate(row.nextCheckDate)
                }}</template>
              </el-table-column>
              <el-table-column label="状态" width="60">
                <template #default="{ row }">
                  {{ row.flag ? '有效' : '失效' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="showDetail(scope.row)"
                    style="margin-right: 10px"
                  >
                    详细
                  </el-button>

                  <el-popconfirm
                    :title="`确定删除 ${scope.row.name} 吗？`"
                    @confirm="remove(scope.row.id)"
                  >
                    <template #reference>
                      <el-button size="small" type="danger"> 删除 </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-row class="page-row">
        <el-col :span="24">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageSize"
            :current-page="currentPage"
            :total="total"
            @current-change="page"
          />
        </el-col>
      </el-row>

      <!-- 添加疫苗弹窗 -->
      <el-dialog title="添加疫苗" v-model="saveDialog" width="600px">
        <el-form :model="vaccineObj" label-width="80px">
          <el-form-item
            label="疫苗名称"
            prop="name"
            :rules="[{ required: true, message: '名称不能为空' }]"
          >
            <el-input
              v-model="vaccineObj.name"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="数量" prop="amount">
            <el-input-number v-model="vaccineObj.amount" :min="0" />
          </el-form-item>
          <el-form-item label="生产时间" prop="productionDate">
            <el-date-picker
              v-model="vaccineObj.productionDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="失效时间" prop="inactivationDate">
            <el-date-picker
              v-model="vaccineObj.inactivationDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="检测时间" prop="nextCheckDate">
            <el-date-picker
              v-model="vaccineObj.nextCheckDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="状态" prop="flag">
            <el-switch
              v-model="vaccineObj.flag"
              active-value="true"
              inactive-value="false"
              active-text="有效"
              inactive-text="失效"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="full-width-button"
              :disabled="!isValid(vaccineObj) || loading"
              @click="vaccineAdd"
            >
              立即添加
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 详细信息弹窗 -->
      <el-dialog
        title="疫苗详细信息"
        v-model="detailDialog"
        width="600px"
        :before-close="
          () => {
            detailDialog = false
          }
        "
      >
        <el-descriptions
          :column="1"
          border
          v-if="detailObj"
          class="detail-desc"
        >
          <el-descriptions-item label="疫苗名称">{{
            detailObj.name
          }}</el-descriptions-item>
          <el-descriptions-item label="疫苗编号">{{
            detailObj.numbering
          }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{
            detailObj.amount
          }}</el-descriptions-item>
          <el-descriptions-item label="生产时间">{{
            formatDate(detailObj.productionDate)
          }}</el-descriptions-item>
          <el-descriptions-item label="失效时间">{{
            formatDate(detailObj.inactivationDate)
          }}</el-descriptions-item>
          <el-descriptions-item label="检测时间">{{
            formatDate(detailObj.nextCheckDate)
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            detailObj.flag ? '有效' : '失效'
          }}</el-descriptions-item>
          <el-descriptions-item label="登记人ID">{{
            detailObj.registrantId
          }}</el-descriptions-item>
          <el-descriptions-item label="登记时间">{{
            formatDate(detailObj.registeredAt)
          }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            formatDate(detailObj.createdAt)
          }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { Search, CirclePlus } from '@element-plus/icons-vue'

const searchVaccine = reactive({ vaccineNumbering: '' })
const vaccineData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

const saveDialog = ref(false)
const loading = ref(false)
const detailDialog = ref(false)

const vaccineObj = reactive({
  name: '',
  amount: null,
  productionDate: '',
  inactivationDate: '',
  nextCheckDate: '',
  flag: true, // 布尔值，默认有效
})

const detailObj = reactive({
  id: null,
  name: '',
  numbering: '',
  amount: null,
  productionDate: '',
  inactivationDate: '',
  nextCheckDate: '',
  flag: true,
  registrantId: '',
  registeredAt: '',
  createdAt: '',
})

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d)) return ''
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

async function loadData() {
  try {
    const res = await axios.get(
      `http://127.0.0.1:8181/vaccines/vaccineList/${currentPage.value}/${pageSize.value}`
    )
    if (res.data && res.data.code === 0) {
      let dataList = res.data.data.data || []
      if (searchVaccine.vaccineNumbering) {
        dataList = dataList.filter((item) =>
          item.numbering.includes(searchVaccine.vaccineNumbering)
        )
      }
      vaccineData.value = dataList
      total.value = res.data.data.total || dataList.length
    }
  } catch (error) {
    alert('加载疫苗数据失败: ' + error.message)
  }
}

onMounted(() => {
  loadData()
})

function page(pageNum) {
  currentPage.value = pageNum
  loadData()
}

function search() {
  currentPage.value = 1
  loadData()
}

function handleSave() {
  saveDialog.value = true
  Object.assign(vaccineObj, {
    name: '',
    amount: null,
    productionDate: '',
    inactivationDate: '',
    nextCheckDate: '',
    flag: true,
  })
}

function isValid(obj) {
  return obj.name && obj.name.trim().length > 0
}

async function vaccineAdd() {
  if (!isValid(vaccineObj)) return
  loading.value = true
  try {
    const postData = {
      name: vaccineObj.name,
      amount: vaccineObj.amount,
      productionDate: vaccineObj.productionDate,
      inactivationDate: vaccineObj.inactivationDate,
      nextCheckDate: vaccineObj.nextCheckDate,
      registrantId: JSON.parse(localStorage.getItem('user')).id,
      flag: vaccineObj.flag, // 布尔值传输
    }
    const res = await axios.post(
      'http://127.0.0.1:8181/vaccines/create',
      postData
    )
    if (res.data && res.data.code === 0) {
      alert('添加成功')
      saveDialog.value = false
      loadData()
    } else {
      alert('添加失败')
    }
  } catch (error) {
    alert('添加请求失败: ' + error.message)
  }
  loading.value = false
}

async function remove(id) {
  try {
    const res = await axios.get(
      `http://127.0.0.1:8181/vaccines/delete/${id}/${currentPage.value}/${pageSize.value}`
    )
    if (res.data && res.data.code === 0) {
      alert('删除成功')
      vaccineData.value = res.data.data.data
      total.value = res.data.data.total
    } else {
      alert('删除失败')
    }
  } catch (error) {
    alert('删除请求失败: ' + error.message)
  }
}

function showDetail(row) {
  Object.assign(detailObj, row)
  detailDialog.value = true
}
</script>

<style scoped>
.page-row {
  margin-top: 20px;
  text-align: center;
}

.search-form {
  margin-bottom: 10px;
}

.full-width-button {
  width: 100%;
}

.table-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.detail-desc {
  word-break: break-word;
}

.el-main {
  padding: 0 !important;
}
</style>
